import React, { useEffect, useState } from "react";

import { Toast } from "antd-mobile";

import { getCityList, getHotCity } from "@/api";
import { getCurrentCity, setCityLocal } from "../../utils";

import { List, AutoSizer } from 'react-virtualized'
import 'react-virtualized/styles.css'

import styles from './index.module.scss'

import NavHeader from '../../components/NavBar'

const INDEX_HEIGHT = 36
const CITY_NAME_HEIGHT = 50
const CITY_SOURCE_ARRAY = ['上海', '北京', '杭州']

const formatCityIndex = (letter) => {
  switch (letter) {
    case '#':
      return '当前城市'
    case 'hot':
      return '热门城市'
    default:
      return letter
  }
}
let cityListRef = React.createRef()
function CityList(props) {
  const [cityList, setCityList] = useState([])
  const [cityIndex, setCityIndex] = useState([])
  const [activeIndex, setActiveIndex] = useState(0)

  useEffect(() => {
    let didCancel = false
    async function fetchData() {
      const {data} = await getCityList()
      const hotRes = await getHotCity()
      const curCity = await getCurrentCity()

      const cityListRes = data.cities

      cityListRes.unshift({initial: 'hot', list: [hotRes.hot_city]})
      cityListRes.unshift({initial: '#', list: [curCity]})

      const cityIndexRes = cityListRes.map(item => item.initial)

      // 处理hook内存泄露问题
      if (!didCancel) {
        setCityList(cityListRes)
        setCityIndex(cityIndexRes)
      }
      // cityListRef.current.measureAllRows()
    }
    fetchData()
    // hook 可以返回一个函数， 在组件销毁前执行
    return () => {
      didCancel = true
    }
  },[])

  const calcRowHeight = ({index}) => {
    const list = cityList[index].list
    return INDEX_HEIGHT + CITY_NAME_HEIGHT * list.length
  }

  const rowRenderer = () => {
    return cityList.map(item => (
      <div key={item.initial} className={styles.city}>
        <div className={styles.title}>{formatCityIndex(item.initial)}</div>
        {item.list.map((city,index) => (
          <div key={index} className={styles.name} onClick={() => handlePickCity(city)}>{city.name}</div>
        ))}
      </div>
    ))
  }

  const handlePickCity = city => {
    if (CITY_SOURCE_ARRAY.indexOf(city.name) >= 0) {
      setCityLocal(city)
      cityList.shift()
      cityList.unshift({initial: '#', list: [city]})
      setCityList(cityList)
      props.history.push('/')
    } else {
      Toast.info('该城市暂无房源数据', 1, null, false)
    }
  }

  const goToCityIndex = index => {
    cityListRef.current.scrollToRow(index)
  }

  const renderCityIndex = () => {
    return cityIndex.map((item, index) => (
        <li
          key={index}
          className={styles['city-index-item']}
          onClick={() => goToCityIndex(index)}
        >
          <span className={index === activeIndex ? styles['index-active']: ''}>{item === 'hot' ? '热' : item}</span>
        </li>
      ))
  }

  const onRowsRendered = ({startIndex}) => {
    if (activeIndex !== startIndex) {
      setActiveIndex(startIndex)
    }
  }

  return (
    <div className={styles['city-list']}>
      <NavHeader children={'城市列表'}></NavHeader>
      <AutoSizer>
        {({height, width}) => (
          <List
            ref={cityListRef}
            height={height}
            rowCount={cityList.length}
            rowHeight={calcRowHeight}
            rowRenderer={rowRenderer}
            onRowsRendered={onRowsRendered}
            width={width}
            scrollToAlignment="start"
          />
        )}
      </AutoSizer>
      <ul className={styles['city-index']}>{renderCityIndex()}</ul>
    </div>
  )
}

export default CityList
